#!/usr/bin/env python
from tempfile import mkstemp
from shutil import move
from os import remove, close
from os import system
def replace(file_path, pattern, subst, count):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file_path)
    for line in old_file:
        new_file.write(line.replace(pattern, subst, count))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

#import fileinput
#import sys
#def replaceAll(file,searchExp,replaceExp,count):
#    for line in fileinput.input(file, inplace=1):
#        if searchExp in line:
#            line = line.replace(searchExp,replaceExp,count)
#        sys.stdout.write(line)

def printUsage():
    print ("Usage: myCppDir [path]")



import os
def genCT(path):
  if path == '':
    path = '.'


  parentDir = os.getcwd()
  os.chdir(path)
  print("\n\ngenerate cscope database and tags under " + os.getcwd())

  #clean legacy temp files
  print("--->clean exist  cscope database and tags under " + os.getcwd())
  if os.path.exists("cscope.files"):
    os.remove("cscope.files")
  if os.path.exists("cscope.in.out"):
    os.remove("cscope.in.out")
  if os.path.exists("cscope.po.out"):
    os.remove("cscope.po.out")
  if os.path.exists("cscope.out"):
    os.remove("cscope.out")
  if os.path.exists("tags"):
    os.remove("tags")

  print("\n")
  #find target files for later cscope and ctags usage
  print("--->find C++ files under "+os.getcwd()+" recursively for cscope")
  findcmd = "find -L . -name '*.c' -o -name '*.h' -o -name '*.cpp' -o -name '*.sig' -o -name '*.cc' -o -name '*.cxx' -o -name '*.hpp' -o -name '*.h++' -o -name '*.hh'> cscope.files"
  os.system(findcmd)

  print("--->update cscope.files relative path to absolute path")
  absPath = os.path.abspath('.')
  replace("cscope.files",".",absPath,1)
  print("--->generate cscope database:: cscope.out cscope.in.out cscope.po.out")
  os.system("cscope -Ubkq")

  #print("--->generate subdir tags database under "+os.getcwd())
  #generate all subdir tags under current directory first
  #alias localtags "find * -type d -exec subdirtags.sh {} \;"
  #tagslocal = "find * -type d -exec subdirtags.sh {} \;"
  #os.system(tagslocal)
  #then generate global tags for current directory
  #alias globaltags "ctags --file-scope=no -R"
  print("--->generate global tags --file-scope=yes database under "+os.getcwd())
  print("\n")
  os.system("ctags  -f tags -F -h .h.H.hh.hpp.h++ --fields=+imnlSfkst  --file-scope=yes -R  --totals=yes ")

  os.chdir(parentDir)

def main(argv):
  """
  if current folder is the only path you want to generate tags and cscope.out, then no args are expected
  if subfolders are provided as args, then current folder is not expected. otherwise will result duplicate tags and cscope.out data entries
  """
  if argv == []:
    path = '.'
    genCT(path)
  else:
    for path in argv :
      if path == '.':
        continue
      genCT(path)

  #try:
  #  path= argv[0]
  #  print("print from main",path)
  #  genCT(path)
  #except:
  #  printUsage()



if __name__ == "__main__":
  import sys
  main(sys.argv[1:]) ## sends all but the scriptname as argument
